﻿namespace Rsdn.Janus.VirtualForums.NewMessages
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using BLToolkit.Data.Linq;
    using Database;
    using DataModel;
    using SmartApp;

    internal class NewMessage_Message : LinearTreeMsg
    {

        public NewMessage_Message(IServiceProvider provider)
            : base(provider)
        {
        }

        protected override void FillChildren()
        {
            // do nothing    
        }

        public void FillChildrenWithMessagesToMe()
        {
            Children = GetNewMessagesList();

            int unreadCount = 0;
            foreach (MsgBase msg in Children)
            {
                msg.EndMapping(null);
                if (msg.IsUnread)
                {
                    unreadCount++;
                }

                // Why read & unread is different fields?
                // msg.IsRead
            }

            Unread = unreadCount;

            //return msg;
        }

        protected IQueryable<IForumMessage> GetMessages(IJanusDataContext db, DateTime lastUpdateDateTime)
        {
            return db.Messages(m => m.Date > lastUpdateDateTime && m.UserID != Config.Instance.SelfId);
            #region SQL
            /*            
            --  SQLite
            -- DECLARE @lastUpdateDateTime DateTime
            -- DECLARE @p1 Int32

            -- SET @lastUpdateDateTime = 01.06.2011 20:48:40
            -- SET @p1 = 9

            SELECT
	            [m].[mid] as [ID],
	            [m].[tid] as [TopicID],
	            [m].[pid] as [ParentID],
	            [m].[gid] as [ForumID],
	            [m].[Subject],
	            [m].[dte] as [Date1],
	            [m].[uid] as [UserID],
	            [m].[uclass] as [UserClass],
	            [m].[UserNick],
	            [m].[Name],
	            [m].[article_id] as [ArticleId],
	            [m].[LastModerated],
	            [m].[Closed],
	            [m].[Message],
	            [m].[IsMarked],
	            [m].[IsRead],
	            [m].[ReadReplies]
            FROM
	            [messages] [m]
            WHERE
	            [m].[dte] > @lastUpdateDateTime AND [m].[uid] <> @p1

            */
            #endregion
        }

        public void FillCounters()
        {
            IForumQueryService forumQueryService = ServiceProvider.GetRequiredService<IForumQueryService>();
            DateTime lastUpdateDate = forumQueryService.LastUpdateDate;
            using (IJanusDataContext db = ServiceProvider.CreateDBContext())
            {
                if (db.IsValid())
                {
                    IQueryable<IForumMessage> forumMessages = GetMessages(db, lastUpdateDate);
                    RepliesCount = forumMessages.Count();
                    UnreadCount = forumMessages.Count(im => !im.IsRead);

                    #region SQL

                    #endregion
                }
            }
        }

        public List<MsgBase> GetNewMessagesList()
        {
            List<MsgBase> ret = null;
            bool loadAll = true;
            SortType sort = Config.Instance.ForumSortCriteria;
            IForumQueryService forumQueryService = ServiceProvider.GetRequiredService<IForumQueryService>();
            DateTime lastUpdateDate = forumQueryService.LastUpdateDate;
            using (var db = ServiceProvider.CreateDBContext())
            {
                IQueryable<IForumMessage> messages = GetMessages(db, lastUpdateDate);

                messages = ForumDBHelper.AppendSortPredicate(messages, sort);

                ForumDisplayConfig displayConfig = Config.Instance.ForumDisplayConfig;
                if (displayConfig.ShowUnreadThreadsOnly)
                {
                    // messages = messages.Where(ti => !ti.Message.IsRead || ti.AnswersUnread > 0);
                }
                #region SQL
                /*
                -  SQLite
                -- DECLARE @lastUpdateDateTime DateTime
                -- DECLARE @p1 Int32

                -- SET @lastUpdateDateTime = 31.05.2011 23:12:49
                -- SET @p1 = 95947

                SELECT
	                [m].[mid] as [ID],
	                [m].[tid] as [TopicID],
	                [m].[pid] as [ParentID],
	                [m].[gid] as [ForumID],
	                [m].[Subject],
	                [m].[dte] as [Date1],
	                [m].[uid] as [UserID],
	                [m].[uclass] as [UserClass],
	                [m].[UserNick],
	                [m].[Name],
	                [m].[article_id] as [ArticleId],
	                [m].[LastModerated],
	                [m].[Closed],
	                [m].[Message],
	                [m].[IsMarked],
	                [m].[IsRead],
	                [m].[ReadReplies]
                FROM
	                [messages] [m]
		                LEFT JOIN [messages] [t1] ON [m].[pid] = [t1].[mid]
                WHERE
	                [m].[dte] > @lastUpdateDateTime AND [t1].[uid] <> @p1
                ORDER BY
	                [m].[dte] DESC
                 */
                #endregion

                if (!(loadAll || displayConfig.MaxTopicsPerForum <= 0))
                {
                    messages = messages.Take(displayConfig.MaxTopicsPerForum);
                }


                Table<IForumMessage> msgTable = db.Messages();
                ret = DataHelper.LoadMessages(ServiceProvider, messages, msgTable);
            }

            return ret;
        }

        public int UnreadCount
        {
            get
            {
                return RepliesUnread;
            }
            set
            {
                RepliesUnread = value;
            }
        }
    }
}